package cn.hamster3.mc.plugin.ball.velocity.listener;

import cn.hamster3.mc.plugin.ball.common.api.BallAPI;
import cn.hamster3.mc.plugin.ball.common.entity.BallPlayerInfo;
import cn.hamster3.mc.plugin.ball.common.event.BallActions;
import cn.hamster3.mc.plugin.ball.common.event.player.BallPlayerLoginEvent;
import cn.hamster3.mc.plugin.ball.common.event.player.BallPlayerPostLoginEvent;
import cn.hamster3.mc.plugin.ball.common.event.player.BallPlayerPreLoginEvent;
import cn.hamster3.mc.plugin.ball.velocity.util.BallVelocityUtils;
import com.velocitypowered.api.event.PostOrder;
import com.velocitypowered.api.event.Subscribe;
import com.velocitypowered.api.event.connection.LoginEvent;
import com.velocitypowered.api.event.connection.PostLoginEvent;
import com.velocitypowered.api.event.connection.PreLoginEvent;
import com.velocitypowered.api.proxy.Player;

public final class BallVelocityMainListener {
    public static final BallVelocityMainListener INSTANCE = new BallVelocityMainListener();

    private BallVelocityMainListener() {
    }

    @Subscribe(order = PostOrder.LATE)
    public void onPreLogin(PreLoginEvent event) {
        BallAPI.getInstance().sendRawBallMessage(
                BallAPI.BALL_CHANNEL,
                BallActions.BallPlayerPreLogin.name(),
                new BallPlayerPreLoginEvent(event.getUsername())
        );
    }

    @Subscribe(order = PostOrder.LATE)
    public void onLogin(LoginEvent event) {
        if (!event.getResult().isAllowed()) {
            return;
        }
        Player player = event.getPlayer();
        BallAPI.getInstance().sendRawBallMessage(
                BallAPI.BALL_CHANNEL,
                BallActions.BallPlayerLogin.name(),
                new BallPlayerLoginEvent(new BallPlayerInfo(
                        player.getUniqueId(), player.getUsername(), "connecting",
                        BallAPI.getInstance().getLocalServerId(), true
                ))
        );
    }

    @Subscribe(order = PostOrder.LATE)
    public void onPostLogin(PostLoginEvent event) {
        Player player = event.getPlayer();
        BallPlayerInfo playerInfo = BallVelocityUtils.getPlayerInfo(player, true);
        BallAPI.getInstance().sendRawBallMessage(
                BallAPI.BALL_CHANNEL,
                BallActions.BallPlayerPostLogin.name(),
                new BallPlayerPostLoginEvent(playerInfo)
        );
    }
}
